/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
    int amountOfTime(TreeNode *root, int start)
    {
        unordered_map<int, vector<int>> adjTable;
        setupAdjTable(root, adjTable, -1);
        int minute = -1;
        queue<int> q;
        q.push(start);
        unordered_set<int> infected;
        infected.insert(start);
        while (!q.empty())
        {
            ++minute;
            int layerSize = q.size();
            for (int i = 0; i < layerSize; ++i)
            {
                int infectedNode = q.front();
                q.pop();
                for (int adjNode : adjTable[infectedNode])
                {
                    if (!infected.count(adjNode))
                    {
                        infected.insert(adjNode);
                        q.push(adjNode);
                    }
                }
            }
        }
        return minute;
    }

    void setupAdjTable(TreeNode *tree, unordered_map<int, vector<int>> &adjTable, int parentVal)
    {
        if (tree->left != nullptr)
        {
            adjTable[tree->val].push_back(tree->left->val);
            setupAdjTable(tree->left, adjTable, tree->val);
        }
        if (tree->right != nullptr)
        {
            adjTable[tree->val].push_back(tree->right->val);
            setupAdjTable(tree->right, adjTable, tree->val);
        }
        if (parentVal > 0)
        {
            adjTable[tree->val].push_back(parentVal);
        }
    }
};